<template>
  <el-form class="login-container" :model="loginForm" ref="LoginForm" hide-required-asterisk>
    <h3>系统登录</h3>
    <el-form-item label="账号" prop="username" :rules="[
            {required:true,message:'账号不能为空'},
          ]">
      <el-input type="input" placeholder="请输入账号" v-model.trim="loginForm.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" :rules="[
            {required:true,message:'账号不能为空'},
          ]" prop="password">
      <el-input type="password" placeholder="请输入密码" v-model.trim="loginForm.password"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="login">登录</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { reactive } from '@vue/reactivity'
import { getCurrentInstance } from '@vue/runtime-core'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  setup() {
    const { proxy } = getCurrentInstance()
    const store = useStore()
    const router = useRouter()
    //双向绑定用reactive
    const loginForm = reactive({
      username: '',
      password: ''
    })
    //登录
    const login = () => {
      proxy.$refs.LoginForm.validate(async valid => {
        if (valid) {
          let res = await proxy.$api.getMenu(loginForm)
          //存入vuex中
          store.commit('setMenu', res.menu)
          store.commit('addMenu', router)
          store.commit('setToken', res.token)
          //进行路由跳转
          router.push({
            name: 'Main'
          })
          ElMessage({
            message: '登录成功',
            type: 'success'
          })
        }else{
          ElMessage({
            showClose: true,
            message: '密码或账号填写错误',
            type: 'error'
          })
        }
      })
    }
    return {
      loginForm,
      login
    }
  }
}
</script>
<style lang="less" scoped>
.login-container {
  width: 350px;
  background-color: #fff;
  border: 1px solid #eaeaea;
  border-radius: 15px;
  padding: 35px 35px 15px 35px;
  box-shadow: 0 0 25px #cacaca;
  margin: 180px auto;
  h3 {
    text-align: center;
    margin-bottom: 20px;
    color: #505450;
    font-weight: bold;
  }
  :deep(.el-form-item__content) {
    justify-content: center;
  }
}
</style>
